package com.haimi.shiguang.utils;

import android.util.Log;

import java.security.MessageDigest;

/**
 * Created by panyuanyuan
 */
public class Md5Util {

    /**
     * MD5 加密算法
     *
     * @param origin
     * @param sort
     * @return
     */
    public static String MD5EncodeUtf8(String origin, String sort, Boolean encode32) {
        origin = origin + sort;
        return MD5Encode(origin, "utf-8", encode32);
    }

    private static String byteArrayToHexString(byte data[], Boolean encode32) {
        StringBuilder resultSb = new StringBuilder();
        for (byte item : data) {
            resultSb.append(byteToHexString(item, encode32));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b, Boolean encode32) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return encode32 ? hexDigits[d1] + hexDigits[d2] : hexDigits[d1];
    }

    /**
     * 返回大写MD5
     *
     * @param origin
     * @param charsetname
     * @return
     */
    private static String MD5Encode(String origin, String charsetname, Boolean encode32) {
        String resultString = origin;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()), encode32);
            } else {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)), encode32);
            }
        } catch (Exception exception) {
            Log.e("MD5Encode", exception.getMessage());
        }
        return resultString.toUpperCase();
    }

    private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
}